package group.rober.dataform.controller;

import group.rober.dataform.exception.DataFormException;
import group.rober.dataform.handler.DataListHandler;
import group.rober.dataform.handler.DataOneHandler;
import group.rober.dataform.handler.impl.BeanDataListHandler;
import group.rober.dataform.handler.impl.BeanDataOneHandler;
import group.rober.dataform.handler.impl.MapDataListHandler;
import group.rober.dataform.handler.impl.MapDataOneHandler;
import group.rober.dataform.model.DataForm;
import group.rober.dataform.model.types.FormDataModelType;
import group.rober.dataform.model.types.FormStyle;
import group.rober.dataform.service.DataFormService;
import group.rober.runtime.holder.ApplicationContextHolder;
import group.rober.runtime.holder.WebHolder;
import group.rober.runtime.kit.ValidateKit;
import group.rober.runtime.model.PaginationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by tisir<yangsong158@qq.com> on 2017-05-30
 */
@RestController
@RequestMapping("/dataform")
public class DataFormController {
    public static class DataFormWrapper{
        DataForm dataForm;
        DataListHandler<?> dataListHandler;
        DataOneHandler<?> dataOneHandler;
    }

    @Autowired
    protected DataFormService dataFormService;

    @Autowired
    protected MapDataListHandler mapDataListHandler;
    @Autowired
    protected MapDataOneHandler mapDataOneHandler;
    @Autowired
    protected BeanDataListHandler<Object> beanDataListHandler;
    @Autowired
    protected BeanDataOneHandler<Object> beanDataOneHandler;

    public DataFormService getDataFormService() {
        return dataFormService;
    }
    public void setDataFormService(DataFormService dataFormService) {
        this.dataFormService = dataFormService;
    }

    /**
     * 查询DataForm定义的元数据
     * @param form DataForm对象地址
     * @return
     */
    @GetMapping("/meta/{form}")
    public DataForm getDataForm(@PathVariable("form") String form){
        DataFormWrapper wrapper = getDataFormWrapper(form);
        return wrapper.dataForm;
    }


    protected DataFormWrapper getDataFormWrapper(String form){
        DataFormWrapper wrapper = new DataFormWrapper();

        DataForm dataForm = dataFormService.getDataForm(form);
        ValidateKit.notNull(dataForm, "DataForm不存在,form=" + form);

        FormStyle formStyle = dataForm.getFormUIHint().getFormStyle();
        switch (formStyle){
            case DataTable:
            case ListCard:
            case TreeTable:
                //先给默认值
                if(dataForm.getDataModelType() == FormDataModelType.DataTable){
                    wrapper.dataListHandler = mapDataListHandler;
                }else if(dataForm.getDataModelType() == FormDataModelType.JavaBean){
                    wrapper.dataListHandler = beanDataListHandler;
                }
                //如果配置了Handler，则使用配置的Handler
                DataListHandler<?> handler1 = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
                if(handler1!=null){
                    wrapper.dataListHandler = handler1;
                }
            case DetailInfo:
                //先给默认值
                if(dataForm.getDataModelType() == FormDataModelType.DataTable){
                    wrapper.dataOneHandler = mapDataOneHandler;
                }else if(dataForm.getDataModelType() == FormDataModelType.JavaBean){
                    wrapper.dataOneHandler = beanDataOneHandler;
                }
                //如果配置了Handler，则使用配置的Handler
                DataOneHandler<?> handler2 = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
                if(handler2!=null){
                    wrapper.dataOneHandler = handler2;
                }
        }

        //如果没有，则作默认值处理
        if(wrapper.dataOneHandler==null&&wrapper.dataListHandler==null){
            throw new DataFormException("DataForm的数据处理Handler实例不存在,form={0}",form);
        }

        return wrapper;
    }


    /**
     * <dt>分页查询</dt>
     * <dd>路径参数:form DataForm的{package}.{id}</dd>
     * <dd>路径参数:param DataForm的查询参数,格式为name1=value1;name2=value2,如果没有,写none</dd>
     * <dd>路径参数:sort DataForm的排序规则参数,格式为name1=asc,name2=desc,如果没有,写none</dd>
     * <dd>路径参数:size 分页大小,如果不分页,写0</dd>
     * <dd>路径参数:index 分页页码,从0开始</dd>
     * 所有的请求参数为filter参数
     * @param form DataForm对象地址
     * @param paramMatrix DataForm参数矩阵
     * @param sortMatrix DataForm排序矩阵
     * @param size 分页大小
     * @param index 分页页码(从0开始)
     * @return
     */
    @GetMapping("/data/list/{form}/{param}/{sort}/{index:[\\d]+}-{size:[\\d]+}")
    public PaginationData<?> queryDataList(@PathVariable("form") String form
            , @MatrixVariable(pathVar = "param") Map<String, Object> paramMatrix
            , @MatrixVariable(pathVar = "sort") Map<String, String> sortMatrix
            , @PathVariable("size") Integer size, @PathVariable("index") Integer index
    ) {
        DataFormWrapper dfw = getDataFormWrapper(form);
        ValidateKit.notNull(dfw.dataListHandler);

        //初始化处理模板，查询模板对应的数据
        dfw.dataListHandler.initDataForm(dfw.dataForm);
        Map<String, ?> filterMap = WebHolder.getRequestParameterMap();
        PaginationData<?> result = dfw.dataListHandler.query(dfw.dataForm, paramMatrix, filterMap,sortMatrix, size, index);

        System.out.println("query:" + paramMatrix);
        System.out.println("filter:" + filterMap);
        System.out.println("sort:" + sortMatrix);
        return result;
    }

    /**
     * 查询单条记录
     * @param form DataForm对象地址
     * @param paramMatrix DataForm参数矩阵
     * @return
     */
    @GetMapping("/data/one/{form}/{param}")
    public Object queryDataOne(@PathVariable("form") String form,@MatrixVariable(pathVar = "param") Map<String, Object> paramMatrix) {
        DataFormWrapper dfw = getDataFormWrapper(form);
        ValidateKit.notNull(dfw.dataOneHandler);

        //处理模板数据
        DataOneHandler<Object> handler = (DataOneHandler<Object>)dfw.dataOneHandler;
        Object ret = handler.query(dfw.dataForm,paramMatrix);
        handler.initDataForm(dfw.dataForm,ret);
        return ret;
    }
//
//    /**
//     * 保存列表
//     * @param form DataForm对象地址
//     * @param dataList 列表数据
//     * @return
//     */
//    @PostMapping("/save/list/{form}/")
//    public List<?> saveDataList(@PathVariable("form") String form, @RequestBody List<MapData> dataList){
//        //取数据以及dataform并进行相关的校验
//        DataForm dataForm = dataFormService.getDataForm(form);
//        ValidateKit.notNull(dataForm,"dataform not found:"+form);
//        ValidateKit.notEmpty(dataList,"the list data is empty");
//        //取绑定在dataform上的数据处理Handler
//        DataListHandler<?> dataListHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
//        ValidateKit.notNull(dataListHandler, "dataform data processing Handler instance does not exist,form=" + form);
//
//        if(dataListHandler instanceof DataBoxListHandler){
//            DataBoxListHandler handler = (DataBoxListHandler)dataListHandler;
//            handler.save(dataForm,(List)dataList);
//        }else if(dataListHandler instanceof BeanListHandler){
//            BeanListHandler<?> handler = (BeanListHandler)dataListHandler;
//            handler.save(dataForm,(List)dataList);
//        }else{
//            throw new DataFormException("dataform processing class "+dataListHandler.getClass()+" is not legal");
//        }
//
//
//        return dataList;
//
//    }
//
//    /**
//     * 保存单条记录
//     * @param form DataForm对象地址
//     * @param dataOne 数据对象
//     * @return
//     */
//    @PostMapping("/save/one/{form}/")
//    public Object saveDataOne(@PathVariable("form") String form, @RequestBody MapData dataOne){
//        //取数据以及dataform并进行相关的校验
//        DataForm dataForm = dataFormService.getDataForm(form);
//        ValidateKit.notNull(dataForm,"dataform not found:"+form);
//        ValidateKit.notEmpty(dataOne,"the list data is empty");
//        //取绑定在dataform上的数据处理Handler
//        DataSingleHandler<?> dataSingleHandler = ApplicationContextHolder.getBeanByClassName(dataForm.getHandler());
//        ValidateKit.notNull(dataSingleHandler, "dataform data processing Handler instance does not exist,form=" + form);
//
//        if(dataSingleHandler instanceof DataBoxSingleHandler){
//            DataBoxSingleHandler handler = (DataBoxSingleHandler)dataSingleHandler;
//            handler.save(dataForm,(MapData)dataOne);
//        }else if(dataSingleHandler instanceof BeanSingleHandler){
////            BeanSingleHandler<?> handler = (BeanSingleHandler)dataSingleHandler;
////            handler.save(dataForm,dataOne);
//        }else{
//            throw new DataFormException("dataform processing class "+dataSingleHandler.getClass()+" is not legal");
//        }
//
//
//        return dataOne;
//
//    }
//
//    /**
//     * 删除列表数据
//     * @param form DataForm对象地址
//     * @param dataList 列表数据对象
//     * @return
//     */
//    @PostMapping("/delete/list/{form}/")
//    public int deleteDataList(@PathVariable("form") String form, @RequestBody List<MapData> dataList){
//        return 0;
//    }
//
//    /**
//     * 删除单个数据
//     * @param form DataForm对象地址
//     * @param dataOne 数据对象
//     * @return
//     */
//    @PostMapping("/delete/one/{form}/")
//    public int deleteDataOne(@PathVariable("form") String form, @RequestBody MapData dataOne){
//        return 0;
//    }
//
//    /**
//     * 调用列表绑定DataHandler的方法
//     * @param form DataForm对象地址
//     * @param method DataHandler的方法名
//     * @param dataList 数据列表
//     * @return
//     */
//    @PostMapping("/invoke/list/{form}/{method}")
//    public Object invokeDataListHandlerMethod(@PathVariable("form") String form,@PathVariable("method") String method, @RequestBody List<DataBox> dataList){
//        return null;
//    }
//
//    /**
//     * 调用列表绑定DataHandler的方法
//     * @param form DataForm对象地址
//     * @param method DataHandler的方法名
//     * @param dataOne 数据对象
//     * @return
//     */
//    @PostMapping("/invoke/one/{form}/{method}")
//    public Object invokeDataOneHandlerMethod(@PathVariable("form") String form,@PathVariable("method") String method, @RequestBody DataBox dataOne){
//        return null;
//    }
//
//    /**
//     * 服务端校验列表数据
//     * @param form DataForm对象地址
//     * @param dataList 数据对象列表
//     * @return
//     */
//    @PostMapping("/validate/list/{form}")
//    public Object validateDataList(@PathVariable("form") String form, @RequestBody List<MapData> dataList){
//        return null;
//    }
//
//    /**
//     * 服务端校验数据对象
//     * @param form DataForm对象地址
//     * @param dataOne 数据对象
//     * @return
//     */
//    @PostMapping("/validate/one/{form}")
//    public Object validateDataOne(@PathVariable("form") String form, @RequestBody MapData dataOne){
//        return null;
//    }



}
